package com.mirror.tk.core.sms.template.impl;

import java.io.IOException;
import java.io.StringWriter;
import java.nio.charset.Charset;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.VelocityEngine;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;

import com.mirror.tk.core.sms.template.TemplateService;

public class FileTemplateServiceImpl implements TemplateService {

	private VelocityEngine velocityEngine = new VelocityEngine();

	private Map<String, String> map = new HashMap<String, String>();

	@Override
	public String getTemplate(String code) {
		return map.get(code);
	}

	@Override
	public String mergeTemplate(String code, String... params) {
		String template = getTemplate(code);
		if (StringUtils.isBlank(template)) {
			throw new RuntimeException("Template Code[" + code + "] Does not exist");
		}

		VelocityContext context = new VelocityContext();
		context.put("msg", Arrays.asList(params));
		StringWriter writer = new StringWriter();
		velocityEngine.evaluate(context, writer, "error", template);
		return writer.toString();
	}

	public void setTemplate(String code, String path) {
		Resource fileRes = new ClassPathResource(path);
		String tplContent = null;
		try {
			tplContent = IOUtils.toString(fileRes.getInputStream(), Charset.defaultCharset());
		} catch (IOException e) {
			throw new RuntimeException("Load SMS Template Error, Detail:[code(" + code + ") path(" + path + ")]", e);
		}

		if (StringUtils.isBlank(tplContent)) {
			throw new RuntimeException("Load SMS Template Is Null, Detail:[code(" + code + ") path(" + path + ")]");
		}

		map.put(code, tplContent);
	}

	public void setSetting(Map<String, String> templateMap) {
		for (Map.Entry<String, String> en : templateMap.entrySet()) {
			setTemplate(en.getKey(), en.getValue());
		}
	}
}
